﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Drawing;
using System.Data.OracleClient;

public partial class uMESCheckingTaskPopupForm : System.Web.UI.Page
{
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESResourceManagementBusiness bll = new uMESResourceManagementBusiness();
    int m_PageSize = 6;
    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：点检反馈";
        master.strTitle = "点检反馈";
        master.ChangeFrame(true);
        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { BindGridData(upageTurning.CurrentPageIndex); });

        if (!IsPostBack)
        {
            Dictionary<string, string> para = new Dictionary<string, string>();

            BindEmployeeInfo(para);
            BindCheckCycle();
            cbDesignEmployee.Checked = true;
            ShowStatusMessage("", true);
        }

    }


    protected void BindCheckCycle()
    {
        ListItem item = new ListItem();
        item = new ListItem("周点检", "0");
        ddlCheckCycle.Items.Add(item);

        item = new ListItem("日点检", "1");
        ddlCheckCycle.Items.Add(item);

        item = new ListItem("临时点检", "2");
        ddlCheckCycle.Items.Add(item);

        ddlCheckCycle.Items.Insert(0, "");
    }

    /// <summary>
    /// 绑定点检人信息
    /// </summary>
    /// <param name="para"></param>
    protected void BindEmployeeInfo(Dictionary<string, string> para)
    {
        DataTable dt = bll.GetEmployeeInfo(para);
        ddlRealCheck.DataTextField = "fullname";
        ddlRealCheck.DataValueField = "employeeid";
        ddlRealCheck.DataSource = dt;
        ddlRealCheck.DataBind();
        ddlRealCheck.Items.Insert(0, "");
    }

    protected void BindPageControl(DataTable dt)
    {
        if (!string.IsNullOrEmpty(dt.Rows[0]["resourceid"].ToString()))
        {
            txtResourceID.Text = dt.Rows[0]["resourceid"].ToString();
        }

    }

    protected void BindGridData(int intIndex)
    {

        uMESPagingDataDTO result = bll.GetResourceTaskInfo(GetQuery(), intIndex, m_PageSize);
        ItemGrid.DataSource = result.DBTable;
        ItemGrid.DataBind();

        //给分页控件赋值，用于分页控件信息显示
        this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
        this.upageTurning.RowCountByPage = m_PageSize;
    }

    protected void ClearControlInfo()
    {
        //ShowStatusMessage("", true);
        txtNotes.Text = string.Empty;
        uwgAppendix.Rows.Clear();
        txtCheckDate.Value = "";
        imShow.ImageUrl = "";
        if (ddlRealCheck.Items.Count > 0)
        {
            ddlRealCheck.SelectedIndex = 0;
        }
    }

    #region 选中行
    protected void ItemGrid_ActiveRowChange(object sender, RowEventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            ClearControlInfo();
            if (e.Row.Cells.FromKey("realcheckdate").Value != null)
            {
                if (Convert.ToDateTime(e.Row.Cells.FromKey("realcheckdate").Value).ToString("yyyy-MM-dd") != "0001-01-01")
                {
                    txtCheckDate.Value = Convert.ToDateTime(e.Row.Cells.FromKey("realcheckdate").Value).ToString("yyyy-MM-dd");
                }
            }

            if (e.Row.Cells.FromKey("realcheckerid").Value != null)
            {
                ddlRealCheck.SelectedValue = e.Row.Cells.FromKey("realcheckerid").Value.ToString();
            }

            if (e.Row.Cells.FromKey("id").Value != null)
            {
                //绑定附件信息
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("ResourceCheckTaskID", e.Row.Cells.FromKey("id").Value.ToString());
                DataTable dt = bll.GetChecktaskappendixinfo(para);

                uwgAppendix.DataSource = dt;
                uwgAppendix.DataBind();

            }


        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }



    protected void uwgAppendix_ActiveRowChange(object sender, RowEventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            imShow.ImageUrl = "";
            UltraGridRow activeRow = uwgAppendix.DisplayLayout.ActiveRow;
            string strFileName = activeRow.Cells.FromKey("SavedName").Text.Trim();

            string strIsTemp = string.Empty;
            if (activeRow.Cells.FromKey("isSuccess").Value != null)
            {
                strIsTemp = activeRow.Cells.FromKey("isSuccess").Value.ToString();
            }
            if (strIsTemp == "1")
            {
                imShow.ImageUrl = "~/CheckTaskAppendix/Temp/" + strFileName;
            }
            else
            {
                imShow.ImageUrl = "~/CheckTaskAppendix/" + strFileName;
            }

        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    #endregion


    /// <summary>
    /// 确定按钮事件
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        try
        {
          
            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
            if (activeRow == null)
            {
                ShowStatusMessage("请选择要确认的记录！", false);
                return;
            }

            if (ddlRealCheck.SelectedItem.Text == "")
            {
                ShowStatusMessage("点检人不能为空！", false);
                return;
            }

            if (txtCheckDate.Value == "" || txtCheckDate.Value == null)
            {
                ShowStatusMessage("点检时间不能为空！", false);
                return;
            }



            string strMessage = string.Empty;
            bool oResult = UpdateData(ref strMessage);


            if (oResult == true)
            {
                String strDocPath = Server.MapPath(Request.ApplicationPath);
                //删除已保存的附件 
                Dictionary<string, string> para = new Dictionary<string, string>();
                para.Add("ResourceCheckTaskID", activeRow.Cells.FromKey("id").Value.ToString());
                DataTable dt = bll.GetChecktaskappendixinfo(para);
                if (dt.Rows.Count > 0)
                {
                    bool isDelete = true;
                    string destFolder = strDocPath + "\\CheckTaskAppendix\\";
                    for (int j = 0; j < dt.Rows.Count; j++)
                    {
                        string strSaveName = dt.Rows[j]["SavedName"].ToString();
                        isDelete = true;
                        for (int h = 0; h < uwgAppendix.Rows.Count; h++)
                        {
                            if (uwgAppendix.Rows[h].Cells.FromKey("isSuccess").Value == null || uwgAppendix.Rows[h].Cells.FromKey("isSuccess").Text == "")
                            {
                                if (uwgAppendix.Rows[h].Cells.FromKey("SavedName").Value.ToString() == strSaveName)
                                {
                                    isDelete = false;
                                    break;
                                }
                            }

                        }
                        if (isDelete == true)
                        {
                            File.Delete(destFolder + strSaveName);
                        }
                    }
                }

                string strUnSuccessFile = string.Empty;
                for (int i = 0; i < uwgAppendix.Rows.Count; i++)
                {

                    ////保存文档
                    string strFileName = uwgAppendix.Rows[i].Cells.FromKey("SavedName").Text.Trim();
                    string strSavePath = strDocPath + "\\CheckTaskAppendix\\Temp\\";
                    string destFolder = strDocPath + "\\CheckTaskAppendix\\";


                    DirectoryInfo directoryInfo = new DirectoryInfo(strSavePath);
                    FileInfo[] files = directoryInfo.GetFiles();

                    foreach (FileInfo file in files) // Directory.GetFiles(srcFolder)
                    {
                        if (file.Name == strFileName)
                        {
                            file.MoveTo(Path.Combine(destFolder, file.Name));
                            File.Delete(strSavePath + file.Name);
                        }
                        // will move all files without if stmt 
                        //file.MoveTo(Path.Combine(destFolder, file.Name));
                    }
                    uwgAppendix.Rows[i].Cells.FromKey("isSuccess").Value = "1";
                }



                //保存附件
                oResult = SaveData(ref strMessage);
                if (oResult == false)
                {
                    strMessage = "附件保存失败！";
                }

                BindGridData(1);
                ClearControlInfo();
            }
            ShowStatusMessage(strMessage, oResult);
        }
        catch (Exception Ex)
        {
            ShowStatusMessage(Ex.Message, false);
        }
    }

    protected bool UpdateData(ref string strMessage)
    {
        bool blResult = true;
        strMessage = string.Empty;
        try
        {
            Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
            DataTable dtUpdate = new DataTable();
            dtUpdate.Columns.Add("TableName");
            dtUpdate.Columns.Add("ID");
            dtUpdate.Columns.Add("TaskStatus");
            dtUpdate.Columns.Add("TaskNotes");
            dtUpdate.Columns.Add("RealCheckDate");
            dtUpdate.Columns.Add("RealCheckerID");
            dtUpdate.Columns.Add("OperateDate");
            dtUpdate.Columns.Add("OperaterID");

            dtUpdate.Rows.Add();
            int intUpdateRow = dtUpdate.Rows.Count - 1;
            dtUpdate.Rows[intUpdateRow]["TableName"] = "ResourceCheckTaskInfo";
            dtUpdate.Rows[intUpdateRow]["ID"] = activeRow.Cells.FromKey("ID").Text + "㊣String";
            dtUpdate.Rows[intUpdateRow]["TaskStatus"] = "1" + "㊣String";
            dtUpdate.Rows[intUpdateRow]["TaskNotes"] = txtNotes.Text + "㊣String";
            dtUpdate.Rows[intUpdateRow]["RealCheckDate"] = txtCheckDate.Value + "㊣Date";
            dtUpdate.Rows[intUpdateRow]["RealCheckerID"] = ddlRealCheck.SelectedValue + "㊣String";
            dtUpdate.Rows[intUpdateRow]["OperateDate"] = DateTime.Now + "㊣Date";
            dtUpdate.Rows[intUpdateRow]["OperaterID"] = userInfo["EmployeeID"] + "㊣String";

            int iResult = bll.UpdateDataToDatabase(dtUpdate, out strMessage);
            if (iResult == -1)
            {
                blResult = false;
            }
            return blResult;
        }
        catch (Exception ex)
        {
            blResult = false;
            strMessage = ex.Message;
        }
        return blResult;

    }

    /// <summary>
    /// 保存信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <returns></returns>
    protected bool SaveData(ref string strMessage)
    {

        UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
        //以字典形式传递参数
        Dictionary<string, object> para = new Dictionary<string, object>();
        DataSet ds = new DataSet();
        DataTable dtMain = new DataTable();
        dtMain.Columns.Add("ID");//表主键
        dtMain.Columns.Add("ResourceCheckTaskID");//设备点检任务表ID
        dtMain.Columns.Add("AppendixName");//附件名称
        dtMain.Columns.Add("Description");//附件描述
        dtMain.Columns.Add("SavedName");//数据库中保存的附件名称
        dtMain.Columns.Add("SequenceNo");//顺序号

        for (int i = 0; i < uwgAppendix.Rows.Count; i++)
        {
            if (uwgAppendix.Rows[i].Cells.FromKey("isSuccess").Value != null)
            {
                if (uwgAppendix.Rows[i].Cells.FromKey("isSuccess").Text == "1")
                {
                    dtMain.Rows.Add();
                    int intAddRow = dtMain.Rows.Count - 1;
                    dtMain.Rows[intAddRow]["ID"] = Guid.NewGuid().ToString() + "㊣String";
                    dtMain.Rows[intAddRow]["ResourceCheckTaskID"] = activeRow.Cells.FromKey("ID").Text + "㊣String";
                    dtMain.Rows[intAddRow]["AppendixName"] = uwgAppendix.Rows[i].Cells.FromKey("AppendixName").Value + "㊣String";
                    dtMain.Rows[intAddRow]["Description"] = uwgAppendix.Rows[i].Cells.FromKey("Description").Value + "㊣String";
                    dtMain.Rows[intAddRow]["SavedName"] = uwgAppendix.Rows[i].Cells.FromKey("SavedName").Value + "㊣String";
                    dtMain.Rows[intAddRow]["SequenceNo"] = (i + 1).ToString() + "㊣Integer";
                }
            }

        }

        dtMain.Rows.Add();
        dtMain.Rows[dtMain.Rows.Count - 1]["ResourceCheckTaskID"] = activeRow.Cells.FromKey("ID").Text + "㊣String";
        ds.Tables.Add(dtMain);
        ds.Tables[ds.Tables.Count - 1].TableName = "CheckTaskAppendixInfo" + "㊣ResourceCheckTaskID";
        //保存数据
        para.Add("dsData", ds);

        bool result = bll.SaveDataToDatabaseNew(para, out strMessage);
        return result;
    }

    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        string strScript = "ShowMessage(\"" + strMessage + "\", " + boolResult.ToString().ToLower() + ");";
        //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
        //ClientScript.RegisterStartupScript(this.GetType(), "", strScript);
        ScriptManager.RegisterStartupScript(UpdatePanel1, this.GetType(), "Message", strScript, true);
    }

    /// <summary>
    /// 验证是否是正整数
    /// </summary>
    /// <param name="inString"></param>
    /// <returns></returns>
    public static bool IsInt(string inString)
    {
        Regex regex = new Regex("^[0-9]*[1-9][0-9]*$");
        return regex.IsMatch(inString.Trim());
    }


    protected void btnDel_Click(object sender, EventArgs e)
    {
        try
        {
            ShowStatusMessage("", true);
            int intTemp = 0;
            for (int i = 0; i < uwgAppendix.Rows.Count; i++)
            {
                if (uwgAppendix.Rows[i].Cells.FromKey("Select").Value.ToString().ToLower() == "true")
                {
                    intTemp += 1;
                }
            }
            if (intTemp == 0)
            {
                ShowStatusMessage("请选择需要删除的附件信息", false);
                return;
            }

            for (int j = uwgAppendix.Rows.Count - 1; j >= 0; j--)
            {
                if (uwgAppendix.Rows[j].Cells.FromKey("Select").Value.ToString().ToLower() == "true")
                {
                    DeleteTempFile(j);
                    uwgAppendix.Rows[j].Delete();
                }
            }

            imShow.ImageUrl = "";

        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }


    protected void DeleteTempFile(int selectRow)
    {
        string strFileName = uwgAppendix.Rows[selectRow].Cells.FromKey("SavedName").Text.Trim();
        String strDocPath = Server.MapPath(Request.ApplicationPath);
        string strSavePath = strDocPath + "\\CheckTaskAppendix\\Temp\\";

        //string strIsTemp = string.Empty;
        //if (uwgAppendix.Rows[selectRow].Cells.FromKey("isSuccess").Value !=null)
        //{
        //    strIsTemp = uwgAppendix.Rows[selectRow].Cells.FromKey("isSuccess").Value.ToString();
        //}
        //strSavePath= strDocPath + "\\CheckTaskAppendix\\";
        //if (strIsTemp=="1")
        //{
        //    strSavePath = strDocPath + "\\CheckTaskAppendix\\Temp\\";
        //}
        DirectoryInfo dir = new DirectoryInfo(strSavePath);
        FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
        foreach (FileSystemInfo j in fileinfo)
        {
            //if (i is DirectoryInfo)            //判断是否文件夹
            //{
            //    DirectoryInfo subdir = new DirectoryInfo(i.FullName);
            //    subdir.Delete(true);          //删除子目录和文件
            //}
            //else
            //{
            //    //如果 使用了 streamreader 在删除前 必须先关闭流 ，否则无法删除 sr.close();
            ////    File.Delete(i.FullName);      //删除指定文件
            //}

            if (j.FullName == (strSavePath + strFileName))
            {
                File.Delete(j.FullName);
            }
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        try
        {
            //ShowStatusMessage(" ", true);

            UltraGridRow activeRow = ItemGrid.DisplayLayout.ActiveRow;
            if (activeRow == null)
            {
                ShowStatusMessage("请选择要确认的记录！", false);
                return;
            }

            var strPath = fileUpload.FileName;

            if (strPath == string.Empty)
            {
                ShowStatusMessage("请选择要添加附件！", false);
                return;
            }



            ////保存文档
            string strFilePath = (fileUpload.FileName).Trim();
            String strDocPath = Server.MapPath(Request.ApplicationPath); // ConfigurationManager.AppSettings("ImportExcelPatch")

            String strFileName = strFilePath.Substring(strFilePath.LastIndexOf("\\") + 1);

            string strFileType = strFileName.Substring(strFileName.LastIndexOf(".") + 1);

            string strAppendixType = ConfigurationManager.AppSettings["AppendixType"]; //AppendixType

            if (strAppendixType.Contains(strFileType.ToLower()) == false)
            {
                ShowStatusMessage("附件类型错误！", false);
                return;
            }

            string strSavePath = string.Empty;
            //
            if (!string.IsNullOrEmpty(strFilePath))
            {
                uwgAppendix.Rows.Add();
                uwgAppendix.Rows[uwgAppendix.Rows.Count - 1].Cells.FromKey("isSuccess").Value = "1";
                uwgAppendix.Rows[uwgAppendix.Rows.Count - 1].Cells.FromKey("AppendixName").Value = (fileUpload.FileName).Trim();
                uwgAppendix.Rows[uwgAppendix.Rows.Count - 1].Cells.FromKey("SavedName").Value = activeRow.Cells.FromKey("ID").Text + DateTime.Now.ToString("yyyyMMddhhmissffff") + "." + strFileType;

                strSavePath = strDocPath + "\\CheckTaskAppendix\\Temp\\" + activeRow.Cells.FromKey("ID").Text + DateTime.Now.ToString("yyyyMMddhhmissffff") + "." + strFileType;
                try
                {
                    Request.Files[0].SaveAs(strSavePath);

                }
                catch
                {
                    uwgAppendix.Rows[uwgAppendix.Rows.Count - 1].Delete();
                }

            }
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    public Dictionary<string, string> GetQuery()
    {
        string strSearchName = txtSearchName.Text.Trim();
        string strSearchNum = txtSearchNum.Text.Trim();
        string strSearchAsset = txtSearchAsset.Text.Trim();
        string strCheckName = txtcheckName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();
        string strCheckCycle = ddlCheckCycle.SelectedValue;

        Dictionary<string, string> result = new Dictionary<string, string>();
        if (strSearchName != "")
        {
            result.Add("Description", strSearchName);//设备名称
        }

        if (strSearchNum != "")
        {
            result.Add("ResourceName", strSearchNum);//设备编号
        }

        if (strSearchAsset != "")
        {
            result.Add("AssetNumber", strSearchAsset);//资产编号
        }

        if (strCheckName != "")
        {
            result.Add("CheckName", strCheckName);//要求点检人
        }

        if (strStartDate != "")
        {
            result.Add("StartDate", strStartDate);
        }

        if (strEndDate != "")
        {
            result.Add("EndDate", strEndDate);
        }

        if (strCheckCycle != "")
        {
            result.Add("CheckCycle", strCheckCycle);
        }
    
        //查询指定的工艺/计划
        Dictionary<string, string> userInfo = Session["UserInfo"] as Dictionary<string, string>;
        string strOprEmployeeID = userInfo["EmployeeID"];
        if (cbDesignEmployee.Checked == true)
        {
            result.Add("PlanCheckerID", strOprEmployeeID);
        }

        result.Add("TaskStatus", "0");

        return result;
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            upageTurning.TxtCurrentPageIndex.Text = "1";
            ItemGrid.Clear();
            ClearControlInfo();
            BindGridData(1);
        }

        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void btnReSet_Click(object sender, EventArgs e)
    {
        try
        {
            ClearSearchControl();
            ClearControlInfo();
        }

        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void ClearSearchControl()
    {
        txtSearchName.Text = string.Empty;
        txtSearchNum.Text = string.Empty;
        txtSearchAsset.Text = string.Empty;
        txtcheckName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        cbDesignEmployee.Checked = true;
        ddlCheckCycle.SelectedIndex = 0;
        ItemGrid.Clear();
    }
}